import java.util.LinkedList;
import java.util.Queue;

/**
 * 130. 被围绕的区域
 * https://leetcode.cn/problems/surrounded-regions/description/
 */
class Solution2 {
    int[] dx = {-1, 1, 0, 0};
    int[] dy = {0, 0, -1, 1};
    int m, n;
    boolean[][] vist;
    public void solve(char[][] board) {
        m = board.length;//行
        n = board[0].length;//列
        vist = new boolean[m][n];

        //先处理边界情况
        for(int i = 0; i < m; i++) {
            //第一列
            if(board[i][0] ==  'O' && !vist[i][0]) {
                bfs(board, i, 0);
            }
            //最后一列
            if(board[i][n - 1] == 'O' && !vist[i][n - 1]) {
                bfs(board, i, n -1);
            }
        }
        for(int i = 0; i < n; i++) {
            //第一行
            if(board[0][i] == 'O' && !vist[0][i]) {
                bfs(board, 0, i);
            }
            //最后一行
            if(board[m - 1][i] == 'O' && !vist[m - 1][i]) {
                bfs(board, m - 1, i);
            }
        }
        //最后遍历一遍，边界情况的标记为true了，当是true的时候就不修改
        for(int i = 0; i < m; i++) {
            for(int j = 0; j < n; j++) {
                if(board[i][j] == 'O' && !vist[i][j]){
                    board[i][j] = 'X';
                }
            }
        }

    }

    public void bfs(char[][] board, int i, int j) {
        Queue<int[]> q = new LinkedList<>();
        q.offer(new int[]{i, j});
        vist[i][j] = true;
        while(!q.isEmpty()){
            int[] tmp = q.poll();
            int a = tmp[0], b = tmp[1];
            for(int k = 0; k < 4; k++) {
                int x = a + dx[k];
                int y = b + dy[k];
                if(x >= 0 && x < m && y >= 0 && y < n && !vist[x][y] && board[x][y] == 'O') {
                    q.offer(new int[]{x, y});
                    vist[x][y] = true;
                }
            }
        }
    }
}